//
//  BaseViewcontroller.swift
//  TravelSwift
//
//  Created by 智蚂优服 on 2018/12/24.
//  Copyright © 2018 智蚂优服. All rights reserved.
//

import Foundation
import UIKit
import EmptyDataSet_Swift
import MJRefresh


open class ZMViewController: UIViewController, EmptyDataSetSource, EmptyDataSetDelegate {
    
    let disposeBag = DisposeBag()
    /// 让外界入的一些定制化信息
    var actions : [String : Any]?
    var rightButtonClick: ((_ sender: UIButton)->())?
        
    open override func viewDidLoad() {
        hbd_barTintColor = .white
        hbd_barShadowHidden = true
        hbd_titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.zm.color333333(), NSAttributedString.Key.font: UIFont.zm.fontSemibold(size: 16)]
        if view.backgroundColor == nil || view.backgroundColor == UIColor.clear {
            view.backgroundColor = .white
        }
        if navigationController != nil && (navigationController?.viewControllers.count)! > 1 {
            setLeftBtn(imgStr: "back_18")
        }
    }
    
    /// 告诉外界的通用回调
    var optionSuccessBlock : ((_ data : Any?) -> ())?
        
    /// 添加左侧图片按钮
    public func setLeftBtn(imgStr: String) -> Void {
        if let btn = customBackButton() {
            navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: btn)
            btn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        } else {
            let btn = UIButton.init(type: .custom)
            btn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
            btn.setImage(UIImage.init(named: imgStr), for: .normal)
            btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: -22, bottom: 0, right: 0)
            navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: btn)
            btn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        }
    }
    
    /// 添加左侧自定义按钮
    public func setLeftCustomBtn(titleStr: String, color: UIColor, font: UIFont) -> Void {
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        btn.setTitle(titleStr, for: .normal)
        btn.titleLabel?.font = font
        btn.setTitleColor(color, for: .normal)
        btn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: btn)
    }
    
    public func customBackButton() -> UIButton? {
        return nil;
    }
    
    /// 添加右侧图片按钮
    public func setRightImgBtn(imgStr: String, _ click: ((_ sender: UIButton)->())? = nil) -> Void {
        rightButtonClick = click
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        btn.setImage(UIImage(named: imgStr), for: .normal)
        btn.contentHorizontalAlignment = .right
        btn.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: btn)
    }
    
    /// 添加右侧自定义按钮
    @discardableResult
    public func setRightCustomBtn(titleStr: String, color: UIColor, font: UIFont, _ click: ((_ sender: UIButton)->())? = nil) -> UIButton {
        rightButtonClick = click
        let btn = UIButton.init(type: .custom)
        btn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        btn.setTitle(titleStr, for: .normal)
        btn.titleLabel?.font = font
        btn.setTitleColor(color, for: .normal)
        btn.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: btn)
        return btn
    }
    
    // MARK: -----------------  MJRefresh  -----------------
    /// 上拉加载，下拉刷新
    /// - Parameter scrollView: scrollView
    public func addRefresh(scrollView: UIScrollView, addHead: Bool = true, addFoot: Bool = true, complete: ((_ refresh : Bool) ->Void)?) {
        if addHead {
            scrollView.mj_header = ZMRefreshView.addNormalRefreshHeaderWithBlock(complete: {
                complete!(true)
            })
        }
        if addFoot {
            scrollView.mj_footer = ZMRefreshView.addBackNormalFooterWithBlock(complete: {
                complete!(false)
            })
        }
    }
    
    // MARK: -----------------  空数据属性，添加  -----------------
    /// 空数据提示文字
    public var emptyTitle = ""
    /// 空数据提示文字字体
    public var emptyTitleFont = UIFont.zm.fontMedium(size: 14)
    /// 空数据提示文字颜色
    public var emptyTitleColor = UIColor.zm.color999999()
    /// 空数据提示图片
    public var emptyImg = ""
    /// 空数据按钮图片，按钮点击方法子类实现
    public var emptyButtonImage = ""
    /// 空数据背景色，默认UIScrollView背景色
    public var emptyBgColor: UIColor?
    /// 空数据是否可以滑动，默认true
    public var emptyScroll = true
    /// 偏移Y
    public var emptyOffset = 0.0
    /// 是否是第一次进入viewwill appear 加载
    public var isFirstViewwillApper = true
    
    /// 添加空数据展示
    public func addNodataScrollView(scrollView: UIScrollView) -> Void {
        scrollView.emptyDataSetSource   = self
        scrollView.emptyDataSetDelegate = self
    }
    
    
    deinit {
        /// 移除Toast
//        ZMToast.hiddenActivity()
        ZMLog(message: "------------------ \(self.classForCoder) 释放")
    }
    
    /// 点击屏幕结束编辑
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if isFirstViewwillApper {
            firstViewWillAppear()
        }
    }
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if isFirstViewwillApper {
            firstViewDidAppear()
            isFirstViewwillApper = false
        }
    }
    /// 第一次进入viewwill会调用该方法
    public func firstViewWillAppear() {
        
    }
    /// 第一次进入viewdidappear会调用该方法
    public func firstViewDidAppear() {
        
    }
    
    /// push到toVc并且干掉自己
    public func replace(_ toVc : UIViewController , _ notLast : Bool = false) {
        navigationController?.pushViewController(toVc, animated: true)
        ZMJumpHelper.destroy(VC: self, classes: [self.classForCoder],notLast)
    }
    
    public func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) {
    }
    
    public func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
        return true
    }
    
    public func spaceHeight(forEmptyDataSet scrollView: UIScrollView) -> CGFloat {
        return 39
    }
}

// MARK: -----------------  导航返回，右侧按钮事件  -----------------
extension ZMViewController {
    /// 返回事件
    @objc func leftBtnClick(sender: UIButton) -> Void {
        navigationController?.popViewController(animated: true)
    }
    
    /// 右侧按钮事件，子类实现
    @objc func rightBtnClick(sender: UIButton) -> Void {
        if let block = rightButtonClick {
            block(sender)
        }
    }
}

// MARK: - EmptyDataSetSource, EmptyDataSetDelegate
extension ZMViewController {
    
    /// 空数据标题
    public func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        let attributes = [NSAttributedString.Key.foregroundColor: emptyTitleColor, NSAttributedString.Key.font: emptyTitleFont]
        return NSAttributedString(string: emptyTitle, attributes: attributes)
    }
    
    /// 空数据图片
    public func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return UIImage(named: emptyImg)
    }
    
    /// 空数据按钮图片
    public func buttonImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? {
        return emptyButtonImage.count > 0 ? UIImage(named: emptyButtonImage) : nil
    }
     
    /// 空数据是否可以滑动
    public func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
        return emptyScroll
    }
    
    /// 空数据背景色
    public func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
        return emptyBgColor == nil ? scrollView.backgroundColor : emptyBgColor
    }
    
    public func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat {
        return CGFloat(emptyOffset)
    }
    
    
   
}

//MARK:--------------------刷新--------------------
extension ZMViewController {
    func refreshHeader(block : @escaping (()->())) -> MJRefreshNormalHeader {
        let header = MJRefreshNormalHeader {
            block()
            }
        header.lastUpdatedTimeLabel!.isHidden = true
        header.stateLabel!.isHidden = true
        return header
    }
    
    func refreshfooter(block : @escaping (()->())) -> MJRefreshAutoNormalFooter {
        let footer = MJRefreshAutoNormalFooter {
            block()
        }
        footer.isRefreshingTitleHidden = true
        return footer
    }
    
    func dealRefresh(table : UITableView,allCount : Int,totalCount : Int) {
        if table.mj_footer != nil {
            if allCount >= totalCount {
                table.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                table.mj_footer?.endRefreshing()
            }
        }
        if table.mj_header != nil {
            table.mj_header?.endRefreshing()
        }
    }

}
